var failed=success=queue=runningCount=createCount=vmIndex=0,start=null,countdown=require('../public/javascripts/countdown'),sdc = require('sdc-clients'),dc_config=require('../config/dc')['poc'],vmapi = new sdc.VMAPI(dc_config.vmapi),readline = require('readline'),rl = readline.createInterface({
	input: process.stdin,
	output: process.stdout
}),_per=0,vm_num=0

rl.question('请输入owner_uuid(customer):\n', function(user_id) {
	rl.question('请输入concurrent(默认等于vm_num):\n', function(per) {
		rl.close()
		user_id=user_id||'7e5f0cd3-5241-601d-d146-9d93c7af0e1b'
		_per=per=per||0
		start=new Date()
		vmapi.listVms({query:"(&(|(state=running)(state=stopped))(owner_uuid="+user_id+"))"},function(err, vms){
			if (err)console.log(err)
			else if(vms.length){
				vm_num=vms.length
				console.log('待删除主机数：',vm_num)
				createCount=runningCount=vms.length
				if(parseInt(per)>0&&parseInt(createCount)>parseInt(per)){
					queue=createCount-per
					createCount=per
					console.log('有'+queue+'台主机进入等待队列！')
				}
				serializeDelete(vms,user_id)
			}else{
				console.log('主机列表为空')
				process.exit(1)
			}
		})
	})
})
function serializeDelete(vms,user_id){
	if(createCount){
		var begin=new Date()
		vmapi.deleteVm({creator_uuid:user_id,uuid:vms.pop().uuid},function (err, obj) {
			var end=new Date()
			if(err){
				errs(err,++vmIndex)
			}else{
				console.log('\n序列化创建第'+(++vmIndex)+'项任务，api响应时间：',countdown(end,begin,countdown.ALL).toString())
				var presentCount=vmIndex
				setTimeout(function(){cometState(obj,'',vms,user_id,begin,presentCount)},500)
			}
			--createCount
			serializeDelete(vms,user_id)
		})
	}
}
function deleteVM(vms,user_id){
	//if(vms.length){
		var begin=new Date()
		vmapi.deleteVm({creator_uuid:user_id,uuid:vms.pop().uuid},function (err, obj) {
			var end=new Date()
			if(err){
				errs(err,++_per)
			}else{
				console.log('\n序列化创建第'+(++_per)+'项任务，api响应时间：',countdown(end,begin,countdown.ALL).toString())
				var presentCount=_per
				setTimeout(function(){cometState(obj,'',vms,user_id,begin,presentCount)},500)
			}
		})
	//}
}
function errs(err,index){
	if(err.body&&err.body.errors)
		for(var e in err.body.errors)
			console.log('!!!!!!!!!!第'+index+'项任务无法创建',err.body.errors[e])
	else console.log('!!!!!!!!!!第'+index+'项任务无法创建',err)
}
var http = require('http');
function cometState(obj,state,vms,user_id,begin,presentCount){
	var options = {
		hostname: '192.168.115.239', 
		path: '/jobs/'+obj.job_uuid,
		method: 'GET',
		headers: {"Accept": "application/json"}
	};
	var req = http.request(options, function (res) {
		var body = '';
		res.setEncoding('utf8');
		res.on('data',function(d){
			body += d;
		}).on('end', function(){
			var jobState=JSON.parse(body).execution
			if(jobState==="succeeded"||jobState==="failed"||jobState==="canceled"){
					var end=new Date()
						vmapi.getVm({uuid:obj.vm_uuid},function(err, vm){
							if(vm.state=='destroyed'){								
								--runningCount
								console.log('\n*********第'+presentCount+'台主机删除完毕,耗时:',countdown(end,begin,countdown.ALL).toString(),jobState,vm.state,++success)
								if(queue){
									--queue
									deleteVM(vms,user_id)
								}
								if(!runningCount){
									console.log('\n所有'+vm_num+'台主机删除完毕，成功'+success+'台，总耗时：',countdown(new Date(),start,countdown.ALL).toString())
									process.exit(1)
								}
							}else{
								++queue
								vms.push({uuid:obj.vm_uuid})
								console.log('\n!!!!!!!!!!第'+presentCount+'台主机删除失败,已加入重试队列！耗时:',countdown(end,begin,countdown.ALL).toString(),jobState,vm.state,++failed)
								if(failed==vm_num){
									console.log('所有主机进入重试队列！系统杯具了？！')
									process.exit(1)
								}
							}
						})
			}else setTimeout(function(){cometState(obj,state,vms,user_id,begin,presentCount)},500)
		});
	}).on('error', function(e) {
		console.log('\n!!!!!!!!!!查询第'+presentCount+'项任务进度异常：' + e.message);
	})
	req.end();
}